﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Zop;

namespace ImgUpload.Controllers
{
    [Produces("application/json")]
    [ApiController]
    public class CloudUploadController : ControllerBase
    {
        private readonly AliyunService _aliYunService;
        private readonly ILogger<CloudUploadController> _logger;
        public CloudUploadController(AliyunService aliYunService, ILogger<CloudUploadController> logger)
        {
            this._aliYunService = aliYunService;
            _logger = logger;
        }

        [HttpPost]
        [Route("Upload/Cloud")]
        public Task<Result> Cloud()
        {
            ImageType? imagetype = null;
            var imgType = Request?.Form["type"].ToString();
            var userName = Request?.Form["code"].ToString();
            if (string.IsNullOrEmpty(imgType))
                return Task.FromResult(Result.ReFailure("参数错误"));
            imagetype = (ImageType)Enum.Parse(typeof(ImageType), imgType.ToLower());

            if (string.IsNullOrEmpty(userName) || imagetype == null)
                return Task.FromResult(Result.ReFailure("参数错误"));
            string file = "";
            foreach (IFormFile formFile in Request.Form.Files.ToList())
            {
                if (formFile.Name == "ImgByte")
                {
                    using (Stream st = formFile.OpenReadStream())
                    {
                        file = _aliYunService.Upload(imagetype.ToString(), userName, st);
                    }
                }
            }
            if (file.Equals(""))
                return Task.FromResult(Result.ReFailure("上传失败"));
            else
                return Task.FromResult(new Result(file, "success"));
        }

        [HttpGet]
        [Route("{type}/{name}")]
        public Task<FileContentResult> Get(string type, string name)
        {
            string filepath = type.ToLower() + "/" + name;
            var buffer = _aliYunService.DownLoad(filepath);
            var resource = File(buffer, "image/jpeg");
            return Task.FromResult(resource);
        }
    }
}